library("osrm")

## set working directory 
setwd("~/Dropbox/World Bank/OTN_LAC/proj_code")

# List country codes you want to look at 
icc_codes = c('CL', 'PE', 'AR', 'CO','PA', 'PY', 'VE', 'BO', 'SV','MX','CR', 'EC', 'GT', 'NI', 'UY')

icc_codes = c('BR')

## Load in list of coordinates for each country 
for (c in 1:length(icc_codes)) { 
  
  code = icc_codes[c]
  
  # load in file of coordinates for that country, created by prepare_osm_data.m
  data <- read.csv(paste0("data/OSMR/", code, "coordinates.csv"))

  # create row identifier 
  data$id <- rownames(data)
  data <- data[, c(6, 1, 2, 3, 4, 5)]
  
  # get travel times between points
  data$travel_time <- 0
  data$travel_distance <- 0
  data$speed <- 0
  
  for (i in 1:nrow(data)) {
   result <- osrmRoute(
      src = data[i, c(1, 2, 3)], ## use these
      dst = data[i, c(1, 4, 5)], overview=FALSE) # durations are given in seconds 
   
   if (length(result) ==0) {
     data$travel_time[i] <- NA
     data$travel_distance[i] <-  NA
     data$speed[i] <- NA
   }
   
   else{
     data$travel_time[i] <- result[1]/60
     data$travel_distance[i] <- result[2]
     data$speed[i] <-result[2]/(result[1]/60)
   }
  }
  
  # export results to csv to use in Matlab 
  write.csv(data, paste0("data/OSMR/", code, "coordinates_wtimes.csv"))
}


